import pdb
import datetime
import time
import MSFile
import os
import threading
import hashlib
import Cookie

def hash(s): return hashlib.md5(s).hexdigest()
def cookie(env):
    if env.has_key('HTTP_COOKIE'): return Cookie.SimpleCookie(env['HTTP_COOKIE'])
    return Cookie.SimpleCookie()
def isValid(cookie):
    if not cookie.has_key('id'): return False
    #if not cookie.has_key('session'): return False
    return True

class MSUser:
    def __init__(self, path, userNameHash):
        self.lock       = threading.Lock()
        self.hash       = userNameHash
        self.storage    = MSFile.File(path, self.hash)
        self.storage.infoname = path + self.hash + '.user'

    def open(self, Locked=False):
        if not Locked: self.lock.acquire()
        try:
            self.storage.open()
        finally:
            if not Locked: self.lock.release()
    def flush(self, Locked=False):
        if not Locked: self.lock.acquire()
        self.storage.lock()
        try:
            self.storage.setInfo( (1, self.storage.meta) )
        finally:
            self.storage.unlock()
            if not Locked: self.lock.release()
    def validate(self, ckie):
        if not isValid(ckie): return False
        self.lock.acquire()
        try:
            #if self.storage.meta.has_key('session_key'):
            #    if self.storage.meta['session_key'] == str(ckie['session'].value): return True
            #return False
            return True
        finally:
            self.lock.release()
    def getCookie(self):
        self.lock.acquire()
        try:
            now = int(time.time())
            key = hash(str(now))
            #expiration = (datetime.datetime.fromtimestamp(now) + datetime.timedelta(seconds=60)).strftime("%a, %d-%b-%Y %H:%M:%S GMT")
            cookie = Cookie.SimpleCookie()
            cookie['id'] = self.hash
            cookie['id']['path'] = '/'
            #cookie['id']['expires'] = expiration
            cookie['session']   = key
            cookie['session']['path'] = '/'
            #cookie['session']['expires'] = expiration
            self.storage.meta['session_key'] = key
            self.flush(True)
            return cookie
        finally:
            self.lock.release()

